// employment-edit.js
Page({
  data: {
    isEdit: false,
    formData: {
      companyName: '',
      position: '',
      startTime: '',
      endTime: '',
      studentId: ''
    },
  },

  onLoad(options) {
    // 获取用户名
    const username = wx.getStorageSync('username');
    this.setData({
      'formData.studentId': username
    });
    if (options.id) {
      this.setData({ isEdit: true });
      this.loadJobData(options.id);
    }
  },

  // 加载已有数据
  async loadJobData(id) {
    wx.request({
      url: `http://192.168.172.134:5000/api/getEmployById/${id}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({ formData: res.data.data });
        } else {
          wx.showToast({ title: '加载数据失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    });
  },

  // 输入框事件处理函数
  onCompanyNameInput(e) {
    this.setData({
      'formData.companyName': e.detail.value
    });
  },
  onPositionInput(e) {
    this.setData({
      'formData.position': e.detail.value
    });
  },

  // 时间选择
  bindStartDateChange(e) {
    this.setData({
      'formData.startTime': e.detail.value
    });
  },

  bindEndDateChange(e) {
    this.setData({
      'formData.endTime': e.detail.value
    });
  },

  // 表单提交
  formSubmit(e) {
    const formData = e.detail.value;
    const { startTime } = this.data.formData;

    // 表单验证
    if (!formData.companyName.trim()) {
      wx.showToast({ title: '请填写公司名称', icon: 'none' });
      return;
    }
    if (!formData.position.trim()) {
      wx.showToast({ title: '请填写职位名称', icon: 'none' });
      return;
    }
    if (!startTime) {
      wx.showToast({ title: '请选择开始时间', icon: 'none' });
      return;
    }

    // 处理保存逻辑
    const result = {
      ...this.data.formData,
    };

    wx.request({
      url: this.data.isEdit ? 'http://192.168.172.134:5000/api/updateEmploy' : 'http://192.168.172.134:5000/api/addEmploymentStatusWx',
      method: 'GET',
      data: result,
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '保存成功' });
          // wx.navigateBack();
        } else {
          wx.showToast({ title: '保存失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    });

    wx.navigateBack();
    wx.showToast({ title: '保存成功' });
  },

  // 取消操作
  handleCancel() {
    wx.navigateBack();
  },

  // 时间格式化
  formatTime(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    return `${year}-${month}`;
  }
});